# -*- coding: utf-8 -*-
import codecs
import os
import zipfile
import urllib
import logging
import datetime

from django.template import Context, Template
from django.conf import settings


_logger = logging.getLogger('book.epub')


class EPubFactory:
    def __init__(self, book):
        self.book = book
        self.files = []
        self.book.images = []

    def get_template(self, file_name):
        file_path = os.path.join(
            settings.BASE_DIR, 'novel', 'templates', )
        for path in file_name.split('/'):
            file_path = os.path.join(file_path, path)
        with codecs.open(file_path, 'r', 'utf-8') as f:
            return Template(f.read())

    def load_images(self):
        if os.path.exists(self.book.folder):
            for img in os.listdir(self.book.folder):
                if os.path.isfile(os.path.join(self.book.folder, img)):
                    self.book.images.append(img)

    def prepare(self):
        if not hasattr(self.book, 'post_at'):
            self.book.post_at = datetime.datetime.now()
        self.load_images()
        toc_template = self.get_template('epub/toc.html')
        opf_template = self.get_template('epub/opf.html')
        chapter_template = self.get_template('epub/chapter.html')
        titlepage_template = self.get_template('epub/titlepage.xhtml')
        self.files.append(
            ('titlepage.xhtml', titlepage_template.render(Context())))
        self.files.append(
            ('content.opf', opf_template.render(Context(self.book.__dict__))))
        self.files.append(
            ('toc.ncx', toc_template.render(Context(self.book.__dict__))))
        for chapter in self.book.chapters:
            name = 'chapter_%d.html' % (chapter.sort_no,)
            if chapter.href == '#':
                ctx = Context({
                    'title': chapter.title,
                    'lines': [],
                })
                self.files.append((name, chapter_template.render(ctx)))

                for child in chapter.children:
                    if not hasattr(child, 'content'):
                        child.content = ''
                        _logger.warning(
                            'can not find content when generate epub chapter')
                        _logger.warning(child.__dict__)
                    name = 'chapter_%d.html' % (child.sort_no,)

                    content = child.content
                    ctx = Context({
                        'sub_title': child.title,
                        'title': chapter.title,
                        'lines': content.split('\n'),
                    })
                    self.files.append((name, chapter_template.render(ctx)))
            else:
                if not hasattr(chapter, 'content'):
                    chapter.content = ''
                    _logger.warning(
                        'can not find content when generate epub chapter')
                    _logger.warning(chapter.__dict__)
                ctx = Context({
                    'title': chapter.title,
                    'lines': chapter.content.split('\n'),
                })
                self.files.append((name, chapter_template.render(ctx)))

    def generate_cover(self):
        pass

    def get_content(self, url):
        req = urllib.request.Request(url)
        req.add_header('User-Agent','Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:63.0) Gecko/20100101 Firefox/63.0')
        req.add_header('Referer',self.book.host)
        content = None
        with urllib.request.urlopen(req) as res:
            content = res.read()
        return content    
    def download_img(self, url):
        return self.get_content(url)

    def download_cover(self):

        if self.book.cover_url[0] == '/':
            url = self.book.host + self.book.cover_url
        else:
            url = self.book.cover_url
        _logger.debug('cover url:' + url)
        return self.get_content(url)

    def generate(self):
        self.prepare()
        archive = zipfile.ZipFile(
            self.book.title + '.epub', "w", zipfile.ZIP_DEFLATED)
        archive.writestr('mimetype', 'application/epub+zip',
                         zipfile.ZIP_STORED)
        archive.writestr(os.path.join(
            'META-INF', 'container.xml'), _CONTAINER_XML_CONTENT)
        for img in self.book.images:
            archive.write(os.path.join(self.book.folder, img), os.path.join(
                'images', img))
        archive.writestr('stylesheet.css',
                         _STYLE_CONTENT)
        archive.writestr('cover_image.jpg',
                         self.download_cover())
        for name, content in self.files:
            archive.writestr(name, content)
        archive.close()


__TITLEPAGE_CONTENT = """

"""


_CONTAINER_XML_CONTENT = '<?xml version="1.0" encoding="UTF-8"?> <container version="1.0" xmlns="urn:oasis:names:tc:opendocument:xmlns:container"> <rootfiles> <rootfile full-path="content.opf" media-type="application/oebps-package+xml" /> </rootfiles> </container>'


_STYLE_CONTENT = """
* { white-space: normal; }
body { margin: 8px; padding: 0px; font-size: 63%; }
li, p { font-size: 1.4em; }
p { text-indent: 2em; line-height: 1.4em; margin-top: 0px; margin-bottom: 10px; }
h1 { text-align: center; font-size: 1.6em; line-height: 1.4em; font-weight: bold; }
h2 { text-align: center; font-size: 1.4em; line-height: 1.2em; font-weight: bold;}
a { color: blue; text-decoration: underline; }
.cover { padding: 20px; text-align: center; }
.cover img { border: solid #CCC 1px; padding: 3px; }
.cover img:hover { background: #EFEFEF; }
.bookinfo ul { padding: 5px; margin: 0px; list-style-type: none; border: solid #CCC 1px; margin-bottom: 6px; }
.bookinfo ul li { padding: 5px; margin: 0px; border-bottom: dotted #CCC 1px; }
.bookinfo ul li pre { font-size: 14px; margin-left: 30px; word-wrap: break-word; word-break: break-all; }
ul.catalog, .content { margin: 2px; padding: 0px; }
ul.catalog li a { display: block; margin: 0px; text-indent: 1.4em; line-height: 1.7em; color: Black; text-decoration: none; }
ul.catalog li { display: block; background-color: #FFF; height:1.7em; overflow: hidden; opacity: 0.8; }
ul.catalog li:hover.even, ul.catalog li:hover { background-color: #3f3f3f; }
ul.catalog li:hover a { color: White; }
ul.catalog li.even { background-color: #EFEFEF; border-bottom-color: #CCC; border-top-color: #999; border-style: solid; border-width: 1px 0px; }
.center{text-align:center;}
"""
